<template>
  <a-checkbox v-model:checked="checked" style="position:absolute;top:0;">模糊查询</a-checkbox>
  <common-search :col-layout="{xxl: 6, xl:8, lg: 8, md: 12, sm: 24, xs: 24}" v-model="query" :formItems="formItems" @search="handleSearch" @reset="handleReset" :show-item="4"></common-search>
  <a-button type="primary" :loading="exportLoading" @click="exports" v-modulePerm="['skuPool:export']">导出</a-button>
  <a-button type="primary" v-modulePerm="['skuPool:allot']" style="margin-left: 10px;" @click="allotModalOpen">批量调拨</a-button>
  <common-table
      :columns="columns"
      @change="handleTableChange"
      :dataSource="dataList"
      v-model:localPagination="page"
      @paginationChange="onPageChange"
      v-model:loading="loading"
      :rowKey="(record) => record.id"
      :scroll="{ x: 'max-content'}"
      :slots="['action','expandedRowRender','shippingDateItem','poolCode']"
      @expand="handleExpandedRowsChange"
  >
    <template #expandedRowRender="{ record }">
      <expand-sku :ref="`expandSku-${record.id}`" :id="record.id" :productSku="record.productSku" :poolCode="record.poolCode" :warehouseCode="record.warehouseCode" :site="record.site" :saleZone="record.saleZone" :headerTime="record.headerTime" :invStatus="record.invStatus" :magentoSellable="record.magentoSellable" :magentoLeft="record.magentoLeft" :magentoOrderQty="record.magentoOrderQty" :amazonSellable="record.amazonSellable" :amazonLeft="record.amazonLeft" :amazonOrderQty="record.amazonOrderQty"/>
    </template>
    <template #shippingDateItem="{record}">
      <div v-if="record.onloadDate!== null">装柜日期:{{record.onloadDate }}</div>
      <div v-if="record.etaDate!== null">到港日期:{{record.etaDate}}</div>
      <div v-if="record.etaSellable!== null">可售日期:{{record.etaSellable}}</div>
    </template>
    <template #poolCode="{record}">
      {{record.poolCode}}
      <a-tooltip v-if="record.shippingRemark">
        <template #title>{{record.shippingRemark}}</template>
        <ExclamationCircleTwoTone two-tone-color="rgba(255,153,42,1)"/>
      </a-tooltip>
    </template>
    <template #action="{ record }">
      <a @click="control(record)" v-modulePerm="['skuPool:allot']">调拨</a>
    </template>
  </common-table>
  <allotModal :isOpen="isOpen" @close="close" :item="item"/>
  <upload-file ref="upLoad" :url="'/ofc/inventory/pool/product/item/batchAllot'" :name="'批量调拨结果'"
               :method="'post'" :title="'批量调拨'" @search="search">
    <template #template>
      <a @click="downLoadTemplate">下载模版</a>
    </template>
  </upload-file>
  <a-modal v-model:open="multipleAllot" title="批量调拨" @cancel="multipleAllot = false;file.value = null">
    <input type="file" ref="file">

    <template #footer>
      <a-button @click="multipleAllot = false;file.value = null">取消</a-button>
      <a-button  type="primary" @click="allot" :loading="uploadLoading">上传</a-button>
    </template>
  </a-modal>
</template>
<script>
export default {
  name:'inventoryPools-skuPool'
}
</script>
<script setup>
import CommonTable from "@/components/commonTable/index.vue";
import CommonSearch from "@/components/commonSearch/index.vue";
import {ref,onMounted,nextTick,getCurrentInstance} from "vue";
import {getManyDictItems} from "@/api/system/dict.js";
import {useSearchTable} from "@/hooks/table/useSearchTable";
import ExpandSku from "@/views/inventoryPools/components/expandSku.vue";
import {getSkuPool} from "@/api/inventoryPools/skuPool.js";
import allotModal from "@/components/modal/allotModal.vue";
import {postFile} from "@utils/service/index.js";
import {message} from "ant-design-vue";
const formItems = ref([
  {
    label:'站点',
    type:'select',
    field:'site',
    options:[]
  },
  {
    type:'',
    field:'fuzzyFlag',
  },
  {
    label:"平台sku",
    type:'input',
    field: 'productSku',
  },
  {
    label:'库存池',
    field:'poolCode',
    type: 'input',
  },
  {
    label:"仓库",
    type:'input',
    field: 'warehouseCode',
  },
  {
    label:"装柜日期",
    type:'rangePicker',
    field: 'time1',
    defaultValue: [],
    showTime:false,
  },
  {
    label: "到港ETA",
    type:'rangePicker',
    field: 'time2',
    defaultValue: [],
    showTime:false,
  },
  {
    label:'待处理',
    type:'select',
    txt:"是：独立站待处理 + 三方待处理 > 0\n" +
        "否：独立站待处理 + 三方待处理 = 0",
    field:'hasSellable',
    options:[]
  },
  {
    label:'异常筛选',
    type:'select',
    txt:"公共库存<0",
    field:'qtyShareLowerThanZero',
    options:[]
  },
])
const {proxy} = getCurrentInstance()
const isOpen = ref(false)
const exportLoading = ref(false)
const multipleAllot = ref(false)
const uploadLoading = ref(false)
const file = ref({})
const upLoad = ref(null)
const item = ref({})
const checked = ref(true)
const { dataList, query, loading, page, search, reset, onPageChange } = useSearchTable({
  searchAPI: getSkuPool,
  queryFactory: () => ({
    status: '',
    columns:'createTime',
  }),
  beforeSearch: () => {
    //处理日期
    if(query.value.time1){
      query.value.onloadDateStart = query.value.time1[0]
      query.value.onloadDateEnd = query.value.time1[1]
    }else{
      delete query.value.onloadDateStart
      delete query.value.onloadDateEnd
    }
    if(query.value.time2){
      query.value.etaDateStart = query.value.time2[0]
      query.value.etaDateEnd = query.value.time2[1]
    }else{
      delete query.value.etaDateStart
      delete query.value.etaDateEnd
    }
    query.value.fuzzyFlag = checked.value
  },
});
const columns = ref([
  {
    title: '站点',
    dataIndex: 'site',
    key: 'site',
    align: 'center',
  },
  {
    title: '销售区域',
    dataIndex: 'saleZone',
    key: 'saleZone',
    align: 'center',
  },
  {
    title: '仓库',
    dataIndex: 'warehouseCode',
    key: 'warehouseCode',
    align: 'center',
  },
  {
    title: '库存池',
    dataIndex: 'poolCode',
    key: 'poolCode',
    align: 'center',
  },
  {
    title: '头程时间',
    dataIndex: 'shippingDateItem',
    key: 'shippingDateItem',
    align: 'center',
  },
  {
    title: '库存类型',
    dataIndex: 'invStatus',
    key: 'invStatus',
    align: 'center',
  },
  {
    title: '平台SKU',
    dataIndex: 'productSku',
    key: 'productSku',
    align: 'center',
  },
  {
    title: '库内库存',
    dataIndex: 'qty',
    key: 'qty',
    align: 'center',
  },
  {
    title: '公共',
    dataIndex: 'qtyShare',
    align: 'center',
  },
  {
    title: '独立站',
    dataIndex: 'magento_order_qty',
    children: [
      {
        title: 'M可售',
        dataIndex: 'magentoSellable',
        key: 'magentoSellable',
        align: 'center',
      },
      {
        title: 'M专属',
        dataIndex: 'magentoLeft',
        key: 'magentoLeft',
        align: 'center',
      },
      {
        title: 'M待处理',
        dataIndex: 'magento_order_qty',
        key: 'magento_order_qty',
        sorter: true,
        sortOrder: null,
        align: 'center',
      },
    ]
  },
  {
    title: '三方平台',
    dataIndex: 'amazon_order_qty',
    children: [
      {
        title: 'A可售',
        dataIndex: 'amazonSellable',
        key: 'amazonSellable',
        align: 'center',
      },
      {
        title: 'A专属',
        dataIndex: 'amazonLeft',
        key: 'amazonLeft',
        align: 'center',
      },
      {
        title: 'A待处理',
        dataIndex: 'amazon_order_qty',
        key: 'amazon_order_qty',
        sortOrder: null,
        sorter: true,
        align: 'center',
      },
    ]
  },
  {
    title: '红人平台',
    dataIndex: 'kol_order_qty',
    children: [
      {
        title: 'K可售',
        dataIndex: 'kolSellable',
        key: 'kolSellable',
        align: 'center',
      },
      {
        title: 'K专属',
        dataIndex: 'kolLeft',
        key: 'kolLeft',
        align: 'center',
      },
      {
        title: 'K待处理',
        dataIndex: 'kol_order_qty',
        key: 'kol_order_qty',
        sorter: true,
        sortOrder: null,
        align: 'center',
      },
    ]
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'center',
  }
])
/**
 * 初始化字典数据
 * @returns {Promise<void>}
 */
const init = async () => {
  try{
    const res = await getManyDictItems({
      dictCodeList:"site,boolean_cn,is_y"
    })
    formItems.value[0].options = res.result.site
    formItems.value[7].options = res.result.boolean_cn
    formItems.value[8].options = res.result.is_y
  }catch (e){
    console.log("e",e)
    message.error(e)
  }
}
/**
 * 展开行
 * @param flag
 * @param record
 */
const handleExpandedRowsChange = (flag,record) => {
  if(flag){
    nextTick(()=>{
      proxy.$refs[`expandSku-${record.id}`].init()
    })
  }
}
const handleTableChange = (pag, filters, sorter) => {
  clearSort()
  columns.value.forEach(item => {
    if(item.dataIndex === sorter.columnKey){
      item.children[2].sortOrder = sorter.order
    }
  })
  if(sorter.order){
    query.value.sortField = sorter.field
    query.value.sortType = sorter.order
  }else {
    query.value.sortField = ''
    query.value.sortType = ''
  }
  search()
}
const clearSort = () => {
  columns.value.forEach(item => {
    if(item.children){
      item.children.forEach(child => {
          if(child.sortOrder){
            child.sortOrder = null
          }
      })
    }
  })
}
const allotModalOpen = () => {
  upLoad.value.handleShow()
}
const handleSearch = () => {
  query.value.sortField = ''
  query.value.sortType = ''
  clearSort()
  search()
}
const handleReset = () => {
  query.value.sortField = ''
  query.value.sortType = ''
  checked.value = true
  clearSort()
  reset()
}
/**
 * 打开调拨窗口
 * @param record
 */
const control = (record) => {
  isOpen.value = true
  item.value = record
}
const close = () => {
  isOpen.value = false
  console.log(page.value)
  search(page.value.pageNo)
}
const exports = async () => {
  try{
    exportLoading.value = true
    const res = await postFile('/ofc/inventory/pool/product/item/export','get',query.value,'sku库存池.xlsx')
  }catch (e) {
    message.error(e)
  }finally {
    exportLoading.value = false
  }
}
const downLoadTemplate = async () => {
  try{
    const res = await postFile('/ofc/inventory/pool/product/item/batchAllotTemplate','get',{},'批量调拨模板.xlsx')
  }catch (e) {
    message.error(e)
  }
}
onMounted(()=>{
  init()
})
</script>
<style scoped>

</style>
